package com.example.shop_2305.detail

import android.R.attr.bitmap
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.util.Log
import android.view.LayoutInflater
import android.widget.ImageView
import androidx.appcompat.app.ActionBar.LayoutParams
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.lib_base.mvvm.BaseActivity
import com.example.lib_base.net.LiveDataBus
import com.example.lib_base.param.OrderDetail
import com.example.lib_base.param.PPreOrder
import com.example.shop_2305.R
import com.example.shop_2305.adapter.CommentAdapter
import com.example.shop_2305.databinding.ActivityDetailBinding
import com.example.shop_2305.utils.GlideUtils
import com.google.zxing.BarcodeFormat
import com.journeyapps.barcodescanner.BarcodeEncoder
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage


@Route(path = "/app/DetailActivity")
class DetailActivity : BaseActivity<ActivityDetailBinding,DetailViewModel>() {
    val imgs = mutableListOf<String>()
    @Autowired
    @JvmField
    var gid = 1
    var attrId = ""//默认选中的属性的id  只有当数据加载完成后才能赋值

    lateinit var commentAdapter: CommentAdapter
    @SuppressLint("MissingInflatedId")
    override fun initView() {
        ARouter.getInstance().inject(this)

        commentAdapter = CommentAdapter()
        binding.rvComment.adapter = commentAdapter
        binding.rvComment.layoutManager = LinearLayoutManager(this)

        viewModel.comment(gid,10,1,"0")


        viewModel.detail(gid,"normal")
        //点击购物车方法
        binding.tvAddCart.setOnClickListener {
            viewModel.addCart(1,attrId,gid)
        }
        binding.tvGocart.setOnClickListener {
            ARouter.getInstance().build("/app/ShopActivity").withInt("index",2).navigation()
        }
        //点击分享图标，弹出一个自定义对话框，显示相应的二维码图片，点击确定实现分享
        binding.ivShare.setOnClickListener {
            val inflate = LayoutInflater.from(this).inflate(R.layout.item_share, null)
            //生成二维码
            val encodeBitmap =
                BarcodeEncoder().encodeBitmap(gid.toString(), BarcodeFormat.QR_CODE, 200, 200)
            //显示二维码
            inflate.findViewById<ImageView>(R.id.iv).setImageBitmap(encodeBitmap)
            AlertDialog.Builder(this)
                .setTitle("分享")
                .setView(inflate)
                .setNegativeButton("取消",null)
                .setPositiveButton("分享"){
                    a,b->
                    val image: UMImage = UMImage(this, encodeBitmap) //bitmap文件
                    ShareAction(this).withText("hello").setDisplayList(SHARE_MEDIA.SINA,SHARE_MEDIA.QQ,SHARE_MEDIA.WEIXIN)
                        .withMedia(image)
                        .setCallback(object :UMShareListener{
                            override fun onStart(p0: SHARE_MEDIA?) {

                            }

                            override fun onResult(p0: SHARE_MEDIA?) {

                            }

                            override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
                                Log.d("sss", "onError: ${p1?.message}")
                            }

                            override fun onCancel(p0: SHARE_MEDIA?) {

                            }
                        }).open();
                }
                .show()
        }
        //点击跳转到 数据库评论界面
        binding.tvComment.setOnClickListener {
            ARouter.getInstance().build("/app/MessageActivity").withInt("gid",gid).navigation()
        }
        //点击立即购买，创建预下单
        binding.tvBuynow.setOnClickListener {
            var pPreOrder = PPreOrder()
            pPreOrder.preOrderType = "buyNow"//在详情页面中购买
            //给参数添加list集合
            val list = mutableListOf<OrderDetail>()
            //没有循环了，只用创建一个orderDetail
            val orderDetail = OrderDetail()
            orderDetail.attrValueId = attrId.toInt()
            orderDetail.productId = gid
            orderDetail.productNum = 1

            list.add(orderDetail)//将设置好的商品信息实体类放到集合中

            pPreOrder.orderDetails = list//将集合设置到参数的字段中



            viewModel.preOrder(pPreOrder)
        }

        //点击收藏实现事件总线
        binding.tvCollect.setOnClickListener {
            LiveDataBus.instance.sendEvent("collect","点击了收藏图标")
        }
    }

    override fun initData() {
        LiveDataBus.instance.getEvent<String>("collect").observe(this){
            ToastUtils.showLong(it)
        }

        viewModel.detailSuccess.observe(this){
            if(it.code==200){
                attrId = it.data.productValue.values.toList()[0].id.toString()
                binding.info = it.data.productInfo
                //原始显示轮播图==>使用绑定适配器实现
                imgs.add(it.data.productInfo.image)
                imgs.add(it.data.productInfo.image)
                imgs.add(it.data.productInfo.image)
                binding.imgs = imgs
                //显示默认选中的规格名称
                binding.tvSku.text = "已选择:${it.data.productValue.keys.toList()[0]}"
               /* binding.banner.setImages(imgs)
                    .setImageLoader(object :ImageLoader(){
                        override fun displayImage(
                            context: Context?,
                            path: Any?,
                            imageView: ImageView?
                        ) {
                            Glide.with(context!!).load(path).into(imageView!!)
                        }
                    })
                    .start()*/
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.detailFail.observe(this){
            ToastUtils.showLong(it)
        }
        viewModel.addSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                //添加成功后展示动画效果   创建一张图片 设置大小 设置图片内容 将图片添加总布局 展示动画效果   图标消失
                val imageview = ImageView(this)
                val layoutParams = LayoutParams(200, 200)
                imageview.layoutParams = layoutParams
                GlideUtils.loadNormal(this,imgs[0],imageview)

                binding.main.addView(imageview)

                val width = windowManager.defaultDisplay.width.toFloat()
                val height = windowManager.defaultDisplay.height.toFloat()

                val transaltionX =
                    ObjectAnimator.ofFloat(imageview, "translationX", 0f, width, width / 3)
                val translationY = ObjectAnimator.ofFloat(imageview, "translationY", 0f, height)

                val animatorSet = AnimatorSet()
                animatorSet.duration = 3000
                animatorSet.play(transaltionX).with(translationY)
                animatorSet.start()
                animatorSet.addListener(object:Animator.AnimatorListener{
                    override fun onAnimationStart(animation: Animator) {

                    }

                    override fun onAnimationEnd(animation: Animator) {
                        //动画结束后
                        binding.main.removeView(imageview)
                    }

                    override fun onAnimationCancel(animation: Animator) {

                    }

                    override fun onAnimationRepeat(animation: Animator) {

                    }
                })

            }
        }
        viewModel.addFail.observe(this){
            ToastUtils.showLong(it)
        }


        viewModel.commentSuccess.observe(this){
            if(it.code==200){
                commentAdapter.data.clear()
                commentAdapter.data.addAll(it.data.list)
                commentAdapter.notifyDataSetChanged()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.commentFail.observe(this){
            ToastUtils.showLong(it)
        }

        viewModel.preOrderSuccess.observe(this){
            if(it.code==200){
                ARouter.getInstance().build("/app/CreateOrderActivity").withString("preOrderNo",it.data.preOrderNo).navigation()
            }
        }
    }

    override fun getViewModel(): Class<DetailViewModel>  = DetailViewModel::class.java

    override fun getLayout(): Int  = R.layout.activity_detail

}